Functions are reusable blocks of code that perform a specific task. They promote code organization, reusability, and modularity, making your code easier to read, maintain, and debug. In this section, we'll explore how to define and use functions in PHP.

Defining Functions

In PHP, you can define your own custom functions using the following syntax:

function function_name($param1, $param2, ...) {
    // Function code goes here
    return $value; // Optional
}

Here's a breakdown of the components: - The `function` keyword is used to declare a new function. - `function_name` is the name you give to the function, following the same rules as variable names (start with a letter or underscore, and can contain letters, numbers, and underscores). - `$param1, $param2, ...` are optional parameters that the function can accept. You can define as many parameters as needed, separated by commas. - The function body, enclosed in curly braces `{ }`, contains the code that will be executed when the function is called. - The `return` statement is optional and is used to return a value from the function.

Here's an example of a simple function that calculates the square of a number:

function calculateSquare($number) {
    $square = $number * $number;
    return $square;
}

Calling Functions

Once you've defined a function, you can call (or invoke) it from anywhere in your code by using its name followed by parentheses `()`.

$result = calculateSquare(5); // $result will be 25
echo $result;

If your function accepts parameters, you need to provide the corresponding arguments when calling it. Arguments are the actual values passed to the function's parameters.

function greetUser($name, $greeting = "Hello") {
    echo "$greeting, $name!";
}

greetUser("Alice"); // Outputs: Hello, Alice!
greetUser("Bob", "Hi"); // Outputs: Hi, Bob!

Parameter Defaults

As shown in the example above, you can define default values for function parameters. If no argument is provided for a parameter when calling the function, the default value will be used.

function calculateArea($length, $width = 10) {
    return $length * $width;
}

echo calculateArea(5); // Outputs: 50 (using the default width of 10)
echo calculateArea(3, 8); // Outputs: 24 (using the provided width of 8)

Variable-length Argument Lists

PHP allows you to define functions that accept a variable number of arguments using the `...` syntax. This is called a variable-length argument list or a variadic parameter.

function sum(...$numbers) {
    $total = 0;
    foreach ($numbers as $num) {
        $total += $num;
    }
    return $total;
}

echo sum(1, 2, 3); // Outputs: 6
echo sum(4, 5, 6, 7, 8); // Outputs: 30

In the example above, the `sum` function accepts any number of arguments, and they are collected into the `$numbers` array. The function then iterates over the array and calculates the sum of all the numbers.

Function Scope

In PHP, variables defined within a function have local scope, meaning they are only accessible within that function. Variables defined outside of any function have global scope and can be accessed from anywhere in the script.

$x = 10; // Global variable

function myFunction() {
    $y = 20; // Local variable
    echo "Inside the function: x = $x, y = $y"; // Outputs: Inside the function: x = 10, y = 20
}

myFunction();
echo "Outside the function: x = $x"; // Outputs: Outside the function: x = 10
// echo "Outside the function: y = $y"; // Error: Undefined variable $y

To access a global variable within a function, you can either use the `global` keyword or the `$GLOBALS` superglobal array.

$x = 10; // Global variable

function myFunction() {
    global $x; // Accessing the global variable
    $x = 20; // Modifying the global variable
    echo "Inside the function: x = $x"; // Outputs: Inside the function: x = 20
}

myFunction();
echo "Outside the function: x = $x"; // Outputs: Outside the function: x = 20

However, it's generally considered better practice to pass global values as function parameters or return values, rather than relying on global variables within functions.

Static Variables

By default, when a function is called, its local variables are created and initialized. When the function completes, these variables are destroyed. However, PHP allows you to persist a local variable's value between function calls using the `static` keyword.

function incrementCounter() {
    static $counter = 0; // Static variable
    $counter++;
    echo "Counter: $counter\n";
}

incrementCounter(); // Outputs: Counter: 1
incrementCounter(); // Outputs: Counter: 2
incrementCounter(); // Outputs: Counter: 3

In the example above, the `$counter` variable is declared as static, which means its value is preserved across multiple calls to the `incrementCounter` function.

Recursive Functions

A recursive function is a function that calls itself. Recursion is a powerful programming technique that can simplify certain types of problems, such as traversing nested data structures or solving mathematical problems that can be broken down into smaller instances of the same problem.

function factorial($n) {
    if ($n == 0) {
        return 1; // Base case
    } else {
        return $n * factorial($n - 1); // Recursive case
    }
}

echo factorial(5); // Outputs: 120 (5 * 4 * 3 * 2 * 1)

In the example above, the `factorial` function calculates the factorial of a number by calling itself with a smaller value until it reaches the base case (`$n == 0`), at which point it returns 1. The recursive calls are then unwound, and the final result is calculated by multiplying the number with the factorial of the previous number.

While recursion can be powerful, it's essential to ensure that your recursive functions have a proper base case to prevent infinite recursion, which can lead to a stack overflow error and crash your program.

Anonymous Functions

PHP also supports anonymous functions, also known as closures. These are functions that are defined without a name and can be assigned to variables or passed as arguments to other functions.

$greetUser = function($name) {
    echo "Hello, $name!";
};

$greetUser("Alice"); // Outputs: Hello, Alice!

Anonymous functions can also access variables from the parent scope, a concept known as closures. This allows you to create functions that "close over" or "capture" variables from their surrounding scope.

$greeting = "Hello";

$greetUser = function($name) use ($greeting) {
    echo "$greeting, $name!";
};

$greetUser("Alice"); // Outputs: Hello, Alice!

In the example above, the `$greeting` variable from the parent scope is captured and made available within the anonymous function using the `use` keyword.

Arrow Functions

Starting from PHP 7.4, you can define anonymous functions using the shorter arrow function syntax, similar to JavaScript's arrow functions.

$square = fn($x) => $x * $x;

echo $square(5); // Outputs: 25

Arrow functions automatically inherit the current scope, making it easier to work with closures.

$greeting = "Hello";

$greetUser = fn($name) => "$greeting, $name!";

echo $greetUser("Alice"); // Outputs: Hello, Alice!

In the example above, the `$greeting` variable is automatically captured by the arrow function without the need for the `use` keyword.

Built-in Functions

PHP comes with a vast library of built-in functions that cover a wide range of tasks, including string manipulation, array operations, file handling, database interaction, and more. You can find a comprehensive list of all built-in functions and their documentation on the official PHP website: https://www.php.net/manual/en/functions.php

Here are a few examples of commonly used built-in functions:

// String functions
$text = "Hello, World!";
echo strlen($text); // Outputs: 13
echo strtoupper($text); // Outputs: HELLO, WORLD!

// Array functions
$numbers = [1, 2, 3, 4, 5];
echo count($numbers); // Outputs: 5
$reversed = array_reverse($numbers);
print_r($reversed); // Outputs: Array ( [0] => 5 [1] => 4 [2] => 3 [3] => 2 [4] => 1 )

// File functions
$file = fopen("example.txt", "r");
while (!feof($file)) {
    echo fgets($file); // Read a line from the file
}
fclose($file);

// Date and time functions
echo date("Y-m-d"); // Outputs: Current date in YYYY-MM-DD format
echo time(); // Outputs: Current Unix timestamp

These built-in functions can significantly simplify your code and save you time by not having to reinvent the wheel for common tasks.

In the next section, we'll explore how to work with forms in PHP, allowing you to capture user input and process it on the server-side.